﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;

using Telerik.Cms.Engine;
using Telerik.Events;

namespace Telerik.Sitefinity.Services.Migration
{
	public partial class MigrationExportService : IMigrationExportService
	{
		public Message GetEventsList()
		{
			List<MigrationItemContentDefinition> output = new List<MigrationItemContentDefinition>();

			foreach (KeyValuePair<string, ContentProviderBase> provider in m_AllProviders)
			{
				// Check if the provider is DefaultEventsProvider
				if (provider.Value is Telerik.Events.Data.DefaultEventsProvider)
				{
					string providerName = provider.Key;
					EventsManager eventsManager = new EventsManager(providerName);

					if (provider.Value.AllowLocalization)
					{
						foreach (var culture in m_Cultures)
						{
							if (culture != m_DefaultCulture)
								System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(culture);

							IList eventsList = eventsManager.GetEvents();
							AddGenericContentGuidToList(eventsList, output, providerName, culture);
						}
					}
					else
					{
						IList eventsList = eventsManager.GetEvents();
						AddGenericContentGuidToList(eventsList, output, providerName, String.Empty);
					}
				}
			}

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetEventsListResponse", output);
		}

		public Message GetSingleEvent(Message eventDefinitionParam)
		{
			MigrationItemContentDefinition param = eventDefinitionParam.GetBody<MigrationItemContentDefinition>();

			EventsManager eventsManager = new EventsManager(param.ProviderName);
			if (!String.IsNullOrEmpty(param.Language))
				System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(param.Language);
			IEvent eventItem = eventsManager.GetEvent(param.Id);

			MigrationEvent result = new MigrationEvent();
			result.RecurringRule = eventItem.RecurringRule;

			GetSingleGenericContentItem(result, eventItem.ContentItem, param.ProviderName, param.Language);

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetSingleEventResponse", result);
		}
	}
}
